# -*- coding: utf-8 -*-
"""AI Worker Web应用 - 项目管理和测试分析系统"""

import sys
from pathlib import Path
from flask import Flask, render_template, request, jsonify, send_file, redirect, url_for
from werkzeug.utils import secure_filename
import time
import json

# 添加路径到Python路径
current_dir = Path(__file__).parent
parent_dir = current_dir.parent
sys.path.insert(0, str(current_dir))
sys.path.insert(0, str(parent_dir / "src"))
sys.path.insert(0, str(parent_dir))

# 导入ai_worker的模块
from src.config import config_manager
from src.database import db
from src.gitlab_analyzer import GitLabMRAnalyzer
from src.test_case_generator import TestCaseGenerator
from src.bug_analyzer import BugAnalyzer
from src.code_fetcher import CodeFetcher

# 导入case_input的模块
from case_input.curl_parser import CurlParser
from case_input.database import Database as CaseInputDB
from case_input.case_executor import CaseExecutor

app = Flask(__name__)

# 配置
app.config['SECRET_KEY'] = 'ai-worker-secret-key'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 16MB
app.config['UPLOAD_FOLDER'] = 'uploads'
ALLOWED_EXTENSIONS = {'docx', 'doc'}

# 确保必要目录存在
for folder in ['uploads', 'output', 'logs', 'data']:
    Path(folder).mkdir(exist_ok=True)

# 初始化case_input数据库
case_db = CaseInputDB('data/test_cases.db')


def allowed_file(filename):
    """检查文件扩展名"""
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


# ==================== 页面路由 ====================

@app.route('/')
def index():
    """统一首页 - 包含AI测试和用例录入两个Tab"""
    return render_template('index.html')


@app.route('/project/create')
def create_project_page():
    """创建项目页面"""
    return render_template('project_create.html')


@app.route('/project/<int:project_id>')
def project_detail_page(project_id):
    """项目详情页面"""
    return render_template('project_detail.html')


@app.route('/project/<int:project_id>/testcases')
def testcases_page(project_id):
    """测试用例页面"""
    return render_template('testcases.html')


@app.route('/project/<int:project_id>/analysis')
def analysis_page(project_id):
    """代码分析页面"""
    return render_template('analysis.html')


# ==================== API路由 ====================

@app.route('/api/projects', methods=['GET'])
def get_projects():
    """获取项目列表"""
    try:
        projects = db.list_projects()
        return jsonify({
            'success': True,
            'projects': projects
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@app.route('/api/projects', methods=['POST'])
def create_project():
    """创建项目"""
    try:
        data = request.get_json()
        
        name = data.get('name')
        description = data.get('description')
        document_type = data.get('document_type')
        document_source = data.get('document_source')
        
        if not name:
            return jsonify({
                'success': False,
                'error': '项目名称不能为空'
            }), 400
        
        # 创建项目
        project_id = db.create_project(
            name=name,
            description=description,
            document_type=document_type,
            document_source=document_source
        )
        
        return jsonify({
            'success': True,
            'project_id': project_id,
            'message': '项目创建成功'
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@app.route('/api/project/<int:project_id>', methods=['GET'])
def get_project(project_id):
    """获取项目详情"""
    try:
        project = db.get_project(project_id)
        if not project:
            return jsonify({
                'success': False,
                'error': '项目不存在'
            }), 404
        
        return jsonify(project)
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@app.route('/api/project/<int:project_id>', methods=['PUT'])
def update_project(project_id):
    """更新项目信息"""
    try:
        data = request.get_json()
        name = data.get('name')
        description = data.get('description')
        document_source = data.get('document_source')
        document_type = data.get('document_type')
        
        if not name:
            return jsonify({
                'success': False,
                'error': '项目名称不能为空'
            }), 400
        
        # 构建更新参数
        update_params = {'name': name, 'description': description}
        if document_source is not None:
            update_params['document_source'] = document_source
        if document_type is not None:
            update_params['document_type'] = document_type
        
        # 更新项目
        db.update_project(project_id, **update_params)
        
        # 返回更新后的项目
        project = db.get_project(project_id)
        return jsonify(project)
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@app.route('/api/project/<int:project_id>', methods=['DELETE'])
def delete_project(project_id):
    """删除项目"""
    try:
        db.delete_project(project_id)
        return jsonify({
            'success': True,
            'message': '项目删除成功'
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@app.route('/api/project/<int:project_id>/testcases', methods=['GET'])
def get_project_testcases(project_id):
    """获取项目的所有测试用例"""
    try:
        testcases = db.get_project_test_cases(project_id)
        return jsonify(testcases if testcases else [])
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@app.route('/api/project/<int:project_id>/analyses', methods=['GET'])
def get_project_analyses(project_id):
    """获取项目的所有代码分析"""
    try:
        analyses = db.get_project_analyses(project_id)
        return jsonify(analyses if analyses else [])
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@app.route('/api/testcase/<int:testcase_id>', methods=['GET'])
def get_testcase(testcase_id):
    """获取单个测试用例"""
    try:
        testcase = db.get_test_case(testcase_id)
        if not testcase:
            return jsonify({
                'success': False,
                'error': '测试用例不存在'
            }), 404
        
        return jsonify({
            'success': True,
            'testcase': testcase
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@app.route('/api/testcase/<int:testcase_id>', methods=['PUT'])
def update_testcase(testcase_id):
    """更新测试用例"""
    try:
        data = request.get_json()
        content = data.get('content')
        
        if not content:
            return jsonify({
                'success': False,
                'error': '用例内容不能为空'
            }), 400
        
        # 检查测试用例是否存在
        testcase = db.get_test_case(testcase_id)
        if not testcase:
            return jsonify({
                'success': False,
                'error': '测试用例不存在'
            }), 404
        
        # 更新测试用例
        db.update_test_case(testcase_id, content)
        
        return jsonify({
            'success': True,
            'message': '更新成功'
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@app.route('/api/testcase/<int:testcase_id>/download', methods=['GET'])
def download_testcase(testcase_id):
    """下载测试用例"""
    try:
        testcase = db.get_test_case(testcase_id)
        if not testcase:
            return jsonify({
                'success': False,
                'error': '测试用例不存在'
            }), 404
        
        # 创建临时文件
        import tempfile
        with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False, encoding='utf-8') as f:
            f.write(testcase.get('content', ''))
            temp_path = f.name
        
        return send_file(
            temp_path,
            as_attachment=True,
            download_name=f"testcase_{testcase_id}.md",
            mimetype='text/markdown'
        )
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@app.route('/api/projects/<int:project_id>/test-cases', methods=['GET'])
def get_project_test_cases(project_id):
    """获取项目的测试用例"""
    try:
        test_cases = db.get_project_test_cases(project_id)
        return jsonify({
            'success': True,
            'test_cases': test_cases
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@app.route('/api/projects/<int:project_id>/test-cases', methods=['POST'])
def create_test_case(project_id):
    """创建测试用例"""
    try:
        data = request.get_json()
        content = data.get('content')
        
        if not content:
            return jsonify({
                'success': False,
                'error': '测试用例内容不能为空'
            }), 400
        
        test_case_id = db.create_test_case(
            project_id=project_id,
            content=content,
            raw_content=content
        )
        
        return jsonify({
            'success': True,
            'test_case_id': test_case_id
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@app.route('/api/test-cases/<int:test_case_id>', methods=['PUT'])
def update_test_case(test_case_id):
    """更新测试用例"""
    try:
        data = request.get_json()
        content = data.get('content')
        
        if not content:
            return jsonify({
                'success': False,
                'error': '测试用例内容不能为空'
            }), 400
        
        db.update_test_case(test_case_id, content)
        
        return jsonify({
            'success': True,
            'message': '更新成功'
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@app.route('/api/project/<int:project_id>/generate-testcase', methods=['POST'])
def generate_testcase_new(project_id):
    """生成测试用例（新接口）"""
    try:
        data = request.get_json()
        
        ai_provider = data.get('ai_provider')
        ai_key_id = data.get('ai_key_id')
        document_type = data.get('document_type')
        document_source = data.get('document_source')
        
        if not ai_provider:
            return jsonify({
                'success': False,
                'error': '请选择AI模型'
            }), 400
        
        if not document_source:
            return jsonify({
                'success': False,
                'error': '请提供文档来源'
            }), 400
        
        try:
            # 创建生成器
            generator = TestCaseGenerator(
                ai_provider=ai_provider,
                key_id=ai_key_id
            )
            
            # 生成测试用例
            if document_type == 'url':
                result = generator.generate_from_url(document_source)
            else:
                result = generator.generate_from_file(document_source)
            
            if not result.get('success'):
                error_msg = result.get('error', '生成测试用例失败')
                return jsonify({
                    'success': False,
                    'error': error_msg
                }), 500
            
            # 保存到数据库
            test_case_id = db.create_test_case(
                project_id=project_id,
                title=f"测试用例 - {ai_provider}",
                content=result.get('content'),
                raw_content=result.get('content')
            )
            
            return jsonify({
                'success': True,
                'test_case_id': test_case_id,
                'content': result.get('content')
            })
            
        except Exception as gen_error:
            error_msg = f'生成过程出错: {str(gen_error)}'
            return jsonify({
                'success': False,
                'error': error_msg
            }), 500
        
    except Exception as e:
        error_msg = f'系统错误: {str(e)}'
        return jsonify({
            'success': False,
            'error': error_msg
        }), 500


@app.route('/api/projects/<int:project_id>/generate-test-case', methods=['POST'])
def generate_test_case(project_id):
    """生成测试用例"""
    try:
        # 更新项目状态为生成中
        db.update_project(project_id, status='generating', error_message=None)
        
        # 获取项目信息
        project = db.get_project(project_id)
        if not project:
            error_msg = '项目不存在'
            db.update_project(project_id, status='failed', error_message=error_msg)
            return jsonify({
                'success': False,
                'error': error_msg
            }), 404
        
        if not project.get('document_source'):
            error_msg = '项目缺少文档来源，请先上传文档或输入飞书链接'
            db.update_project(project_id, status='failed', error_message=error_msg)
            return jsonify({
                'success': False,
                'error': error_msg
            }), 400
        
        try:
            # 创建生成器
            generator = TestCaseGenerator(
                ai_provider=project.get('ai_provider', 'doubao'),
                key_id=project.get('ai_key_id')
            )
            
            # 生成测试用例
            if project.get('document_type') == 'url':
                result = generator.generate_from_url(project['document_source'])
            else:
                result = generator.generate_from_file(project['document_source'])
            
            if not result.get('success'):
                error_msg = result.get('error', '生成测试用例失败')
                db.update_project(project_id, status='failed', error_message=error_msg)
                return jsonify({
                    'success': False,
                    'error': error_msg
                }), 500
            
            # 保存到数据库
            test_case_id = db.create_test_case(
                project_id=project_id,
                content=result.get('content'),
                raw_content=result.get('content')
            )
            
            # 更新项目状态为成功
            db.update_project(project_id, status='generated', error_message=None)
            
            return jsonify({
                'success': True,
                'test_case_id': test_case_id,
                'content': result.get('content')
            })
            
        except Exception as gen_error:
            error_msg = f'生成过程出错: {str(gen_error)}'
            db.update_project(project_id, status='failed', error_message=error_msg)
            return jsonify({
                'success': False,
                'error': error_msg
            }), 500
        
    except Exception as e:
        error_msg = f'系统错误: {str(e)}'
        try:
            db.update_project(project_id, status='failed', error_message=error_msg)
        except:
            pass
        return jsonify({
            'success': False,
            'error': error_msg
        }), 500


def get_file_context_from_codes(project_name: str, file_path: str, codes_base_dir: str = "codes") -> str:
    """
    从codes目录读取文件的完整内容作为上下文
    
    Args:
        project_name: 项目名称
        file_path: 文件相对路径
        codes_base_dir: codes目录的基础路径
    
    Returns:
        文件内容，如果读取失败返回错误信息
    """
    try:
        # 构建完整路径
        full_path = Path(codes_base_dir) / project_name / file_path
        
        if not full_path.exists():
            return f"[文件不存在: {file_path}]"
        
        # 读取文件内容
        with open(full_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 限制文件大小，避免过大文件
        max_size = 50000  # 50KB字符
        if len(content) > max_size:
            return content[:max_size] + f"\n\n... (文件过大，已截断，共{len(content)}字符)"
        
        return content
    except Exception as e:
        return f"[读取文件失败: {str(e)}]"


@app.route('/api/project/<int:project_id>/analyze', methods=['POST'])
def analyze_code(project_id):
    """执行代码分析"""
    try:
        data = request.get_json()
        
        ai_provider = data.get('ai_provider', 'doubao')
        ai_key_id = data.get('ai_key_id')
        selected_projects = data.get('projects', [])
        test_case_id = data.get('test_case_id')
        mr_urls = data.get('mr_urls', [])  # 支持多个MR地址
        
        # 兼容旧的单个MR地址
        if not mr_urls and data.get('mr_url'):
            mr_urls = [data.get('mr_url')]
        
        if not selected_projects or len(selected_projects) == 0:
            return jsonify({
                'success': False,
                'error': '请至少选择一个项目'
            }), 400
        
        if not mr_urls or len(mr_urls) == 0:
            return jsonify({
                'success': False,
                'error': '请至少提供一个MR地址'
            }), 400
        
        # 获取项目信息
        project = db.get_project(project_id)
        if not project:
            return jsonify({
                'success': False,
                'error': '项目不存在'
            }), 404
        
        # 获取测试用例
        if test_case_id:
            test_case = db.get_test_case(test_case_id)
            if not test_case:
                return jsonify({
                    'success': False,
                    'error': '测试用例不存在'
                }), 404
            test_case_content = test_case['content']
        else:
            # 使用最新的测试用例
            test_cases = db.get_project_test_cases(project_id)
            if not test_cases:
                return jsonify({
                    'success': False,
                    'error': '请先生成测试用例'
                }), 400
            test_case = test_cases[0]
            test_case_id = test_case['id']
            test_case_content = test_case['content']
        
        # 步骤1: 拉取项目代码
        print(f"开始拉取项目代码: {[p['name'] for p in selected_projects]}")
        fetcher = CodeFetcher()
        fetch_result = fetcher.fetch_projects(selected_projects)
        
        if not fetch_result['success']:
            return jsonify({
                'success': False,
                'error': f"代码拉取失败: {fetch_result.get('error', '未知错误')}"
            }), 500
        
        # 步骤2: 分析多个GitLab MR
        print(f"开始分析{len(mr_urls)}个MR")
        config = config_manager.get_config()
        gitlab_config = config.get('gitlab', {})
        gitlab_token = gitlab_config.get('private_token', '')
        
        analyzer = GitLabMRAnalyzer(private_token=gitlab_token if gitlab_token else None)
        
        all_code_changes = []
        all_changed_files = []  # 收集所有改动的文件
        
        for mr_url in mr_urls:
            print(f"  - 分析MR: {mr_url}")
            mr_result = analyzer.analyze_mr(mr_url.strip())
            
            if not mr_result.get('success'):
                return jsonify({
                    'success': False,
                    'error': f'MR分析失败({mr_url}): ' + mr_result.get('error', '未知错误')
                }), 500
            
            all_code_changes.append({
                'url': mr_url,
                'summary': mr_result['summary'],
                'changes': mr_result.get('changes', [])
            })
            
            # 收集所有改动的文件路径
            for change in mr_result.get('changes', []):
                file_path = change.get('new_path') or change.get('old_path', '')
                if file_path and not change.get('deleted_file'):
                    all_changed_files.append(file_path)
        
        print("MR 所有改动文件列表：")
        print(all_changed_files)
        # 组合所有MR的代码变更
        code_changes = "# MR代码变更分析\n\n"
        for idx, mr_change in enumerate(all_code_changes, 1):
            code_changes += f"## MR {idx}: {mr_change['url']}\n\n{mr_change['summary']}\n\n"
        
        # 添加项目信息（不包含完整代码，只是上下文信息）
        project_info = "\n\n# 涉及的项目信息\n\n"
        project_info += "本次分析涉及以下项目代码（代码已本地拉取，分析时将根据MR变更按需查找相关代码）：\n\n"
        for proj in selected_projects:
            project_info += f"- **{proj['name']}**: {proj['repo_url']} (分支: {proj.get('default_branch', proj.get('branch', 'test'))})\n"
        
        # 从codes目录读取改动文件的完整内容作为上下文
        file_contexts = "\n\n# 改动文件的完整上下文\n\n"
        file_contexts += "以下是MR中改动文件的完整内容，用于提供更完整的代码上下文：\n\n"
        
        # 去重文件列表
        unique_files = list(set(all_changed_files))
        print(f"开始读取 {len(unique_files)} 个改动文件的上下文...")
        
        for file_path in unique_files[:20]:  # 限制最多20个文件，避免prompt过大
            # 尝试从所有选中的项目中查找文件
            file_found = False
            for proj in selected_projects:
                project_name = proj['name']
                content = get_file_context_from_codes(project_name, file_path)
                
                if not content.startswith('[文件不存在'):
                    file_contexts += f"## 文件: {file_path}\n"
                    file_contexts += f"**项目**: {project_name}\n\n"
                    file_contexts += f"```\n{content}\n```\n\n"
                    file_found = True
                    print(f"  ✓ 读取文件: {project_name}/{file_path}")
                    break
            
            if not file_found:
                print(f"  ✗ 文件未找到: {file_path}")
        
        # 组合完整内容：MR变更 + 文件上下文 + 项目信息
        full_content = code_changes + file_contexts + project_info
        
        # 步骤3: Bug分析
        print("开始AI分析...")
        bug_analyzer = BugAnalyzer(
            ai_provider=ai_provider,
            key_id=ai_key_id
        )
        
        analysis_result = bug_analyzer.analyze(full_content, test_case_content)
        
        if not analysis_result.get('success'):
            return jsonify({
                'success': False,
                'error': '分析失败: ' + analysis_result.get('error', '未知错误')
            }), 500
        
        # 格式化报告
        report = bug_analyzer.format_analysis_report(analysis_result) if hasattr(bug_analyzer, 'format_analysis_report') else str(analysis_result.get('analysis', ''))
        
        # 删除该项目的所有旧分析（只保留最新结果）
        print(f"删除项目 {project_id} 的旧分析结果...")
        db.delete_project_analyses(project_id)
        
        # 保存分析记录
        project_names = ', '.join([p['name'] for p in selected_projects])
        mr_urls_str = '; '.join(mr_urls)  # 多个MR用分号分隔
        
        analysis_id = db.create_code_analysis(
            project_id=project_id,
            test_case_id=test_case_id,
            mr_url=mr_urls_str,  # 保存所有MR地址
            projects_info=json.dumps(selected_projects, ensure_ascii=False)
        )
        
        db.update_code_analysis(
            analysis_id,
            analysis_result=report,
            status='completed'
        )
        
        return jsonify({
            'success': True,
            'analysis': {
                'id': analysis_id,
                'result': report,
                'projects': project_names,
                'mr_urls': mr_urls,
                'mr_count': len(mr_urls),
                'codes_fetched': fetch_result['success_count'],
                'ai_provider': ai_provider
            }
        })

    except Exception as e:
        import traceback
        traceback.print_exc()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@app.route('/api/upload', methods=['POST'])
def upload_file():
    """上传文件"""
    try:
        if 'file' not in request.files:
            return jsonify({
                'success': False,
                'error': '没有文件'
            }), 400
        
        file = request.files['file']
        if file.filename == '':
            return jsonify({
                'success': False,
                'error': '没有选择文件'
            }), 400
        
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            timestamp = int(time.time())
            safe_filename = f"{timestamp}_{filename}"
            
            file_path = Path(app.config['UPLOAD_FOLDER']) / safe_filename
            file.save(file_path)
            
            return jsonify({
                'success': True,
                'file_path': str(file_path),
                'filename': filename
            })
        else:
            return jsonify({
                'success': False,
                'error': '不支持的文件格式'
            }), 400
            
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@app.route('/api/models')
def get_models():
    """获取可用的模型列表"""
    try:
        models = []
        config = config_manager.get_config()
        
        # 豆包模型
        doubao_config = config.get('doubao', {})
        keys = doubao_config.get('keys', {})
        for key_id, key_config in keys.items():
            models.append({
                'provider': 'doubao',
                'key_id': key_id,
                'name': key_config.get('name', f'豆包-{key_id}'),
                'model': key_config.get('model', 'doubao-pro')
            })
        
        # DeepSeek模型
        deepseek_config = config.get('deepseek', {})
        if deepseek_config.get('api_key'):
            models.append({
                'provider': 'deepseek',
                'key_id': '',
                'name': 'DeepSeek',
                'model': deepseek_config.get('model', 'deepseek-chat')
            })
        
        # Gemini模型
        gemini_config = config.get('gemini', {})
        if gemini_config.get('api_key'):
            models.append({
                'provider': 'gemini',
                'key_id': '',
                'name': 'Gemini',
                'model': gemini_config.get('model', 'gemini-pro')
            })
        
        return jsonify({
            'success': True,
            'models': models
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@app.route('/api/gitlab/projects')
def get_gitlab_projects():
    """获取GitLab项目配置"""
    try:
        config = config_manager.get_config()
        gitlab_config = config.get('gitlab', {})
        projects = gitlab_config.get('projects', [])
        
        return jsonify({
            'success': True,
            'projects': projects,
            'gitlab_url': gitlab_config.get('base_url', 'https://gitlab.com')
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@app.route('/api/case-modules')
def get_case_modules():
    """获取Case录入模块配置"""
    try:
        config = config_manager.get_config()
        modules = config.get('case_modules', ['自定义分析', '业务报表', '看板', '显著性分析', '数据订阅'])
        
        return jsonify({
            'success': True,
            'modules': modules
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@app.route('/api/code/fetch', methods=['POST'])
def fetch_code():
    """拉取项目代码"""
    try:
        data = request.get_json()
        projects = data.get('projects', [])
        
        if not projects:
            return jsonify({
                'success': False,
                'error': '没有要拉取的项目'
            }), 400
        
        # 创建代码拉取器
        fetcher = CodeFetcher()
        
        # 执行拉取
        result = fetcher.fetch_projects(projects)
        
        if result['success']:
            return jsonify(result)
        else:
            return jsonify(result), 500
            
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@app.route('/api/code/clean', methods=['POST'])
def clean_code():
    """清理代码目录"""
    try:
        fetcher = CodeFetcher()
        result = fetcher.clean_codes()
        return jsonify(result)
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


# ==================== Case Input API路由 ====================

@app.route('/api/case-input/cases', methods=['GET'])
def get_case_input_cases():
    """获取所有测试用例（用例录入）"""
    try:
        cases = case_db.get_all_cases()
        return jsonify({
            'success': True,
            'data': cases
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@app.route('/api/case-input/cases/<int:case_id>', methods=['GET'])
def get_case_input_case(case_id):
    """获取单个测试用例（用例录入）"""
    try:
        case = case_db.get_case(case_id)
        if case:
            # 获取该case的参数
            params = case_db.get_parameters(case_id)
            case['parameters'] = params
            return jsonify({
                'success': True,
                'data': case
            })
        else:
            return jsonify({
                'success': False,
                'error': '测试用例不存在'
            }), 404
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@app.route('/api/case-input/cases', methods=['POST'])
def create_case_input_case():
    """创建测试用例（从curl命令）"""
    try:
        data = request.json
        title = data.get('title', '').strip()
        module = data.get('module', '').strip()
        curl_command = data.get('curl_command', '').strip()
        
        if not title:
            return jsonify({
                'success': False,
                'error': '标题不能为空'
            }), 400
        
        if not curl_command:
            return jsonify({
                'success': False,
                'error': 'curl命令不能为空'
            }), 400
        
        # 解析curl命令
        parser = CurlParser(curl_command)
        parsed = parser.parse()
        
        if not parsed['domain']:
            return jsonify({
                'success': False,
                'error': '无法解析curl命令，请检查格式'
            }), 400
        
        # 保存到数据库
        case_id = case_db.create_case(
            title=title,
            domain=parsed['domain'],
            url_path=parsed['url_path'],
            method=parsed['method'],
            headers=parsed['headers'],
            body=parsed['body'],
            full_url=parsed['full_url'],
            module=module if module else None
        )
        
        return jsonify({
            'success': True,
            'data': {
                'case_id': case_id,
                'parsed': parsed
            }
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@app.route('/api/case-input/cases/<int:case_id>', methods=['PUT'])
def update_case_input_case(case_id):
    """更新测试用例（用例录入）"""
    try:
        data = request.json
        
        success = case_db.update_case(
            case_id=case_id,
            title=data['title'],
            domain=data['domain'],
            url_path=data['url_path'],
            method=data['method'],
            headers=data['headers'],
            body=data['body']
        )
        
        if success:
            return jsonify({
                'success': True,
                'message': '更新成功'
            })
        else:
            return jsonify({
                'success': False,
                'error': '测试用例不存在'
            }), 404
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@app.route('/api/case-input/cases/<int:case_id>', methods=['DELETE'])
def delete_case_input_case(case_id):
    """删除测试用例（用例录入）"""
    try:
        success = case_db.delete_case(case_id)
        
        if success:
            return jsonify({
                'success': True,
                'message': '删除成功'
            })
        else:
            return jsonify({
                'success': False,
                'error': '测试用例不存在'
            }), 404
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@app.route('/api/case-input/cases/<int:case_id>/execute', methods=['POST'])
def execute_case_input_case(case_id):
    """执行测试用例（用例录入）"""
    try:
        # 获取测试用例
        case = case_db.get_case(case_id)
        if not case:
            return jsonify({
                'success': False,
                'error': '测试用例不存在'
            }), 404
        
        # 获取所有参数（用于参数化）
        all_params = case_db.get_all_parameters()
        
        # 创建执行器并执行
        executor = CaseExecutor(all_params)
        success, result = executor.execute(case)
        
        # 保存执行记录
        case_db.save_execution_record(
            case_id=case_id,
            status_code=result['status_code'] or 0,
            response_body=json.dumps(result['response_body'], ensure_ascii=False) if result['response_body'] else None,
            response_headers=result['response_headers'],
            execution_time=result['execution_time'],
            success=success,
            error_message=result['error_message']
        )
        
        return jsonify({
            'success': True,
            'data': result
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@app.route('/api/case-input/cases/<int:case_id>/parameters', methods=['POST'])
def save_case_input_parameter(case_id):
    """保存参数（用例录入）"""
    try:
        data = request.json
        param_name = data.get('param_name', '').strip()
        param_value = data.get('param_value', '').strip()
        json_path = data.get('json_path', '').strip()
        
        if not param_name or not param_value:
            return jsonify({
                'success': False,
                'error': '参数名和参数值不能为空'
            }), 400
        
        case_db.save_parameter(
            case_id=case_id,
            param_name=param_name,
            param_value=param_value,
            json_path=json_path or None
        )
        
        return jsonify({
            'success': True,
            'message': '参数保存成功'
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@app.route('/api/case-input/cases/<int:case_id>/parameters', methods=['GET'])
def get_case_input_parameters(case_id):
    """获取测试用例的所有参数（用例录入）"""
    try:
        params = case_db.get_parameters(case_id)
        return jsonify({
            'success': True,
            'data': params
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@app.route('/api/case-input/parameters', methods=['GET'])
def get_all_case_input_parameters():
    """获取所有参数（用例录入）"""
    try:
        params = case_db.get_all_parameters()
        return jsonify({
            'success': True,
            'data': params
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@app.route('/api/case-input/cases/<int:case_id>/history', methods=['GET'])
def get_case_input_execution_history(case_id):
    """获取执行历史（用例录入）"""
    try:
        limit = request.args.get('limit', 10, type=int)
        records = case_db.get_execution_records(case_id, limit)
        return jsonify({
            'success': True,
            'data': records
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


if __name__ == '__main__':
    config = config_manager.get_config()
    server_config = config.get('server', {})
    
    host = server_config.get('host', '0.0.0.0')
    port = server_config.get('port', 5003)
    debug = server_config.get('debug', True)
    
    print("=" * 50)
    print("  🚀 AI Worker 启动中...")
    print("=" * 50)
    print(f"  访问地址: http://localhost:{port}")
    print(f"  调试模式: {'开启' if debug else '关闭'}")
    print("=" * 50)
    
    # 禁用reloader避免路径问题
    app.run(host=host, port=port, debug=debug, use_reloader=False)
